package com.xhga.register;

import org.I0Itec.zkclient.ZkClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 选择服务
 * Created by Hua wb on 2018/11/29.
 */
public class RpcDiscover {

    private ZkClient zkClient;

    private List<String> dataList = new ArrayList<String>();

    public RpcDiscover() {
        zkClient = new ZkClient(ZkConfig.LOCALHOST, ZkConfig.SESSION_TIMEOUT);
        initServerAddress();
    }

    public String discoverServer() {
        int index = new Random().nextInt(dataList.size());
        return dataList.get(index);
    }

    private void initServerAddress() {
        try {
            List<String> children = zkClient.getChildren(ZkConfig.PATH);
            for (String node:children) {
                String serverAddress = zkClient.readData(ZkConfig.PATH + "/" + node).toString();
                dataList.add(serverAddress);
            }
        } catch (Exception e) {
            System.out.println("register:请检测zookeeper server是否启动/或找不到服务端.");
        }
    }
}
